; (function ($, window, undefined) {
    "use strict"
    var complex, ulitity, Variable = {}, currentVariable, scrollVariable = {}, currentObject;

    ulitity = {
        ie: function () {
            var userAgent = navigator.userAgent.toLowerCase();
            return ((/msie/.test(userAgent) && !/opera/.test(userAgent)) || /trident/.test(userAgent));
        }(),
        render: function () {
            var _html = "<div class=\"input-group\">";
            _html += "  <input type=\"text\" class=\"form-control\" disabled=\"disabled\">";
            _html += "  <span class=\"input-group-btn\">";
            _html += "      <button type=\"button\" class=\"btn btn-default\">";
            _html += "          <i class=\"glyphicon glyphicon-search\"></i>";
            _html += "      </button>";
            _html += "  </span>";
            _html += "</div>";
            return _html;
        },
        container: function () {
            var _html = "<div class=\"complex-container\">";
            _html += "   <div class=\"complex-header\">";
            _html += "       <div class=\"col-sm-12 complex-header-search\">";
            _html += "           <div class=\"input-group\">";
            _html += "               <div class=\"input-group-btn\">";
            _html += "                   <button type=\"button\" class=\"btn btn-default dropdown-toggle\">";
            _html += "                       <span class=\"complex-type\">用户</span> <span class=\"caret\"></span>";
            _html += "                   </button>";
            _html += "                   <button type=\"button\" class=\"btn btn-default search-icon\">";
            _html += "                       <span class=\"glyphicon glyphicon-search\"></span>";
            _html += "                   </button>";
            _html += "                   <ul class=\"dropdown-menu\">";
            var _compose = currentVariable.options.compose;
            if (!_compose || _compose.indexOf("user") > -1) {
                _html += "                       <li value='user'><a>用户</a></li>";
            }
            if (!_compose || _compose.indexOf("dept") > -1) {
                _html += "                       <li value='dept'><a>部门</a></li>";
            }
            if (!_compose || _compose.indexOf("custom") > -1) {
                _html += "                       <li value='custom'><a>角色</a></li>";
            }
            // if (!_compose || _compose.indexOf("common") > -1) {
            //     _html += "                       <li value='common'><a>通用角色</a></li>";
            // }
            _html += "                   </ul>";
            _html += "                 </div>";
            _html += "                 <input type=\"text\" class=\"form-control search-input\">";
            _html += "                 <div class=\"input-group-btn search-right\">";
            _html += "                   <button type=\"button\" class=\"btn btn-default search-clear\">";
            _html += "                       <span class=\"glyphicon glyphicon-remove\"></span>";
            _html += "                   </button>";
            _html += "                   <button type=\"button\" class=\"btn btn-default  search-cancel\">";
            _html += "                       取消";
            _html += "                   </button>";
            _html += "                 </div>";
            _html += "             </div>";
            _html += "        </div>";
            _html += "   </div>";
            _html += "   <div class=\"complex-body\">";
            _html += "       <div class=\"complex-body-content\" id='complex-body-content'>";
            _html += "           <div class='c-b-c-search'>";
            _html += "              <div class='c-b-c-s-empty'></div>";
            _html += "           </div>";
            _html += "           <div class='c-b-c-list'>";
            _html += "              <ul></ul>";
            _html += "           </div>";
            _html += "       </div>";
            _html += "   </div>";
            _html += "   <div class=\"complex-footer\">";
            _html += "       <div class=\"complex-footer-btn\">";
            _html += "           <button class=\"btn btn-primary\" type=\"button\">";
            _html += "               确定<span class=\"badge\">0</span>";
            _html += "           </button>";
            _html += "       </div>";
            _html += "       <div class=\"complex-footer-selected\">";
            _html += "           <div class=\"complex-selected-body\"  id='complex-selected-body'>";
            _html += "               <ul></ul>";
            _html += "           </div>";
            _html += "       </div>";
            _html += "    </div>";
            _html += "</div>";
            return _html;
        },
        screen: {
            width: function () {
                return $(window).width();
            }(),
            height: function () {
                return $(window).height();
            }()
        },
        mobile: function () {
            return !!navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
        }(),
        event: {
            fix: function (layer) {
                $(layer).find(".layermcont").css({ "padding": "0" });
                var width = 960, height = 500;
                if (ulitity.mobile) {
                    width = ulitity.screen.width;
                    height = ulitity.screen.height;
                    $(layer).find(".layermanim").css({ "width": width + "px", "height": height + "px", "max-width": "100%" });
                } else {
                    if (ulitity.screen.width < width) {
                        width = ulitity.screen.width;
                    }
                    if (ulitity.screen.height < height) {
                        height = ulitity.screen.height - 60;
                    }
                }
                $(layer).find(".complex-container").css({ "width": width + "px", "height": (height - 46) + "px" });
                ulitity.event.back(layer);
                ulitity.event.menu(layer);
                ulitity.event.right(layer);
                ulitity.event.confirm(layer);
                ulitity.event.search(layer);
                ulitity.event.clear(layer);
                ulitity.event.cancel(layer);
                ulitity.event.remove(layer);
            },
            menu: function (layer) {
                $(layer).off("click", "button.dropdown-toggle");
                $(layer).on("click", "button.dropdown-toggle", function (e) {
                    e.stopPropagation();
                    $(layer).find("ul.dropdown-menu").toggleClass("show");
                });
                ulitity.event.item(layer);
            },
            item: function (layer) {
                $(layer).off("click", "ul.dropdown-menu");
                $(layer).on("click", "ul.dropdown-menu li", function (e) {
                    e.stopPropagation();
                    var _text = $(this).text(),
                        _value = $(this).attr("value");
                    $(layer).find(".complex-type").html(_text);
                    $(layer).find("ul.dropdown-menu").toggleClass("show");

                    currentVariable.options.type = _value;

                    var _initNo = ulitity.init.type(_value);
                    ulitity.post(layer, _initNo);

                    if ($(layer).find("button.search-cancel").is(":visible")) {
                        $(layer).find("button.search-cancel").trigger("click");
                    }
                });
            },
            right: function (layer) {
                $(layer).off("click", ".body-item-right");

                $(layer).on("click", ".body-item-middle", function (e) {
                    var _type = currentVariable.options.type;
                    if (_type == "dept" && $(layer).find(".search-right").is(':visible')) { return; }
                    if (_type == "user" || _type == "custom" || _type == "common") {
                        $(this).prev().prev().trigger("click");
                    } else if (_type == "dept") {
                        ulitity.post(layer, $(this).attr("no"));
                    }
                });

                $(layer).on("click", ".body-item-right", function (e) {
                    e.stopPropagation();
                    if ($(this).find(".single").length > 0) {
                        /*单选*/
                        if ($(layer).find("#complex-selected-body li[type='" + $(this).attr("type") + "']").length > 0) {
                            $(layer).find(".single.selected").removeClass("selected");
                            $(layer).find("#complex-selected-body li[type='" + $(this).attr("type") + "']").remove();
                        }
                        $(this).find(".single").addClass("selected");
                        ulitity.event.selected(layer, $(this));
                    } else if ($(this).find(".multy").length > 0) {
                        /*多选*/
                        $(this).find(".multy").toggleClass("selected");
                        ulitity.event.selected(layer, $(this));
                    } else {
                        /*下一级*/
                        ulitity.post(layer, $(this).attr("no"));
                    }
                });
            },
            selected: function (layer, object) {
                var _name = $(object).attr("name"),
                    _no = $(object).attr("no"),
                    _type = $(object).attr("type"),
                    $selectedBody = $(layer).find(".complex-selected-body ul");

                if ($(object).find(".selected").length > 0) {
                    var _insertHtml = $(ulitity.tmpl.selected()).filter("#tmpl").tmpl({
                        rows: [
                            { name: _name, no: _no, type: _type }
                        ]
                    });
                    $selectedBody.append(_insertHtml);
                } else {
                    $selectedBody.find("#s_" + _no).remove();
                }
                ulitity.event.count(layer);
            },
            back: function (layer) {
                $(layer).off("click", ".layer_back");
                $(layer).on("click", ".layer_back", function (e) {
                    e.stopPropagation();
                    if ($(layer).find(".search-right").is(':visible')) { return; }
                    var _grand = $(layer).find(".complex-body-content li:first").attr("grand");
                    if (!_grand) { return; }
                    ulitity.post(layer, _grand);
                });
            },
            confirm: function (container) {
                $(container).on("click", ".complex-footer-btn button", function (e) {
                    e.stopPropagation();
                    var liArray = $("#complex-selected-body li"),
                        result = [],
                        inputText = "";
                    $(liArray).each(function () {
                        var _name = $(this).attr("name"),
                            _no = $(this).attr("no"),
                            _type = $(this).attr("type");

                        inputText += _name + ",";
                        if (_no == "3001") {
                            _no = _name;
                            _type = "ProductLine";
                        }
                        if (_type == "ApprovalRole") {
                            _no = _no.replace('-', '|');
                        }

                        result.push({ name: _name, no: _no, type: _type });
                    });
                    if (inputText.length > 0) {
                        inputText = inputText.substring(0, inputText.length - 1);
                    }

                    currentObject.parent().prev().val(inputText);

                    currentObject.parents("div[complex-key]").attr("value", JSON.stringify(result));

                    currentVariable.exec('confirm', result);

                    layer.close($(container).attr("index"));
                });
            },
            clear: function (layer) {
                $(layer).on("click", "button.search-clear", function (e) {
                    $(layer).find("input.search-input").val("");
                });
            },
            cancel: function (layer) {
                $(layer).on("click", "button.search-cancel", function (e) {
                    $(layer).find("input.search-input").val("");
                    $(layer).find(".c-b-c-list").show();
                    $(layer).find(".c-b-c-search").hide().html(ulitity.empty());
                    $(layer).find("input.search-input").removeClass("focus");
                });
            },
            remove: function (layer) {
                $(layer).on("click", "i.selected-close", function (e) {
                    var $obj = $(this).parent(),
                        _no = $obj.attr("no"),
                        _type = $obj.attr("type"),
                        _name = $obj.attr("name");

                    var $cObj = (_type == "UnitRole" ? $("[c_name='n_" + _name + "']") : $("#component_" + _no));
                    $cObj.removeClass("selected");

                    $obj.remove();
                    ulitity.event.count(layer);
                });
            },
            count: function (layer) {
                var $selectedBody = $(layer).find(".complex-selected-body ul"),
                    count = $selectedBody.find("li").length;

                var $badge = $(layer).find("span.badge");
                $badge.html(count);
                if (count == 0) {
                    $badge.hide();
                } else {
                    if (count > 9) {
                        $badge.css({ "display": "inline-block", "padding": "3px" });
                    } else {
                        $badge.css({ "display": "inline-block" });
                    }
                }

                ulitity.scroll.selected();
            },
            search: function (layer) {
                var $input = $(layer).find("input.search-input");
                $input.on("focus", function () {
                    $(layer).find(".c-b-c-list").hide();
                    $(layer).find(".c-b-c-search").show();
                    $input.addClass("focus");

                }).on("input propertychange", function () {
                    if ($(this).prop('comStart')) return;
                    ulitity.post(layer, $(this).val(), true);
                }).on("compositionstart", function () {
                    $(this).prop('comStart', true);
                }).on("compositionend", function () {
                    $(this).prop('comStart', false);
                    if (!ulitity.ie) {
                        ulitity.post(layer, $(this).val(), true);
                    }
                });
            }
        },
        post: function (layer, id, search) {
            if (search) {
                id = id.replace(/[\%\^\&\*\{\}\:\"\L\<\>\?\|\+\.]/g, '');
                if (!id) {
                    /*完善空搜索*/
                    return;
                }
                if (!isNaN(id) && id.length < 5) return;
            }

            var _url = (!search ? currentVariable.options.url : currentVariable.options.search_url) + "/" + id,
                _parameter = currentVariable.options.parameter,
                _container = search ? $(layer).find(".complex-body-content .c-b-c-search") : $(layer).find(".complex-body-content .c-b-c-list ul");

            AJAXAPI(_url, _parameter, function (d) {
                if (!d || d.length == 0) {
                    if (search) {
                        _container.html(ulitity.empty());
                    }
                    ShowError("无数据显示");
                    return;
                }

                var tmplHtml = $(ulitity.tmpl.list()).filter("#tmpl").tmpl({
                    rows: d
                });
                _container.empty();
                if (search) {
                    _container.append("<ul></ul>");
                    _container.find("ul").append(tmplHtml);
                } else {
                    _container.append(tmplHtml);
                }

                ulitity.init.selected();
            });
        },
        empty: function () {
            return "<div class='c-b-c-s-empty'></div>";
        },
        tmpl: {
            right: {
                custom: function (multy) {

                    var _tmpl = "";
                    _tmpl += "<div class=\"body-item-right\" name='${Name}' no='${No}' type='CustomRole'>";
                    _tmpl += "{{if IsDept == '1'}}";
                    _tmpl += "      <div class=\"b-i-r-component arrow-next\"></div>";
                    _tmpl += "{{else}}";
                    _tmpl += "  {{if !" + multy + "}}";
                    _tmpl += "      <div class=\"b-i-r-component single\" id='component_${No}'></div>";
                    _tmpl += "  {{else}}";
                    _tmpl += "      <div class=\"b-i-r-component multy\" id='component_${No}'></div>";
                    _tmpl += "  {{/if}}";
                    _tmpl += "{{/if}}";
                    _tmpl += "  </div>";
                    return _tmpl;
                },
                user: function (multy) {
                    var _tmpl = "";
                    _tmpl += "<div class=\"body-item-right\" name='${Name}' no='${No}' type='UserNO'>";
                    _tmpl += "{{if IsDept == '1'}}";
                    _tmpl += "      <div class=\"b-i-r-component arrow-next\"></div>";
                    _tmpl += "{{else}}";
                    _tmpl += "  {{if !" + multy + "}}";
                    _tmpl += "      <div class=\"b-i-r-component single\" id='component_${No}'></div>";
                    _tmpl += "  {{else}}";
                    _tmpl += "      <div class=\"b-i-r-component multy\" id='component_${No}'></div>";
                    _tmpl += "  {{/if}}";
                    _tmpl += "{{/if}}";
                    _tmpl += "  </div>";
                    return _tmpl;
                },
                dept: function (multy) {
                    var _tmpl = "";
                    _tmpl += "<div class=\"body-item-right\" name='${Name}' no='${No}' type='UnitNO'>";
                    _tmpl += "  {{if !" + multy + "}}";
                    _tmpl += "      <div class=\"b-i-r-component single\" id='component_${No}'></div>";
                    _tmpl += "  {{else}}";
                    _tmpl += "      <div class=\"b-i-r-component multy\" id='component_${No}'></div>";
                    _tmpl += "  {{/if}}";
                    _tmpl += "  </div>";
                    return _tmpl;
                },
                common: function (multy) {
                    var _tmpl = "";
                    _tmpl += "<div class=\"body-item-right\" name='${Name}' no='${No}' type='${GrandName}'>";
                    _tmpl += "{{if IsDept == '1'}}";
                    _tmpl += "      <div class=\"b-i-r-component arrow-next\"></div>";
                    _tmpl += "{{else}}";
                    _tmpl += "  {{if !" + multy + "}}";
                    _tmpl += "      <div class=\"b-i-r-component single\" id='component_${No}' c_name='n_${Name}'></div>";
                    _tmpl += "  {{else}}";
                    _tmpl += "      <div class=\"b-i-r-component multy\" id='component_${No}' c_name='n_${Name}'></div>";
                    _tmpl += "  {{/if}}";
                    _tmpl += "{{/if}}";
                    _tmpl += "  </div>";
                    return _tmpl;
                }
            },
            middle: {
                user: function () {
                    var _tmpl = "";
                    _tmpl += "      <div class=\"b-i-m-top ellipsis\">";
                    _tmpl += "{{if IsDept == '1'}}";
                    _tmpl += "          ${Name}";
                    _tmpl += "{{else}}";
                    // _tmpl += "  {{if IsDepart == '1'}}";
                    // _tmpl += "      <font style=\"color:#c80000\">[离职]</font>";
                    // _tmpl += "  {{/if}}";
                    _tmpl += "          ${Name}（${No}）";
                    _tmpl += "{{/if}}";
                    _tmpl += "      </div>";
                    // _tmpl += "      <div class=\"b-i-m-bottom ellipsis\">";
                    // _tmpl += "{{if IsDept == '1'}}";
                    // _tmpl += "          ${DeptPName}";
                    // _tmpl += "{{else}}";
                    // _tmpl += "          ${DeptPName} / ${FEmail} / ${FPostName}";
                    // _tmpl += "{{/if}}";
                    // _tmpl += "      </div>";
                    return _tmpl;
                },
                dept: function () {
                    var _tmpl = "";
                    _tmpl += "      <div class=\"b-i-m-top ellipsis\">";
                    _tmpl += "{{if IsDept == '1'}}";
                    _tmpl += "          ${Name}";
                    _tmpl += "{{else}}";
                    _tmpl += "          ${Name}（${No}）";
                    _tmpl += "{{/if}}";
                    _tmpl += "      </div>";
                    _tmpl += "      <div class=\"b-i-m-bottom ellipsis\">";
                    _tmpl += "          ${DeptPName}";
                    _tmpl += "      </div>";
                    return _tmpl;
                },
                custom: function () {
                    var _tmpl = "";
                    _tmpl += "      <div class=\"b-i-m-top ellipsis\">";
                    _tmpl += "          ${Name}";
                    _tmpl += "      </div>";
                    _tmpl += "      <div class=\"b-i-m-bottom ellipsis\">";
                    _tmpl += "          ${DeptPName}";
                    _tmpl += "      </div>";
                    return _tmpl;
                },
                common: function () {
                    var _tmpl = "";
                    _tmpl += "      <div class=\"b-i-m-top ellipsis\">";
                    _tmpl += "          ${Name}";
                    _tmpl += "      </div>";
                    _tmpl += "      <div class=\"b-i-m-bottom ellipsis\">";
                    _tmpl += "          ${DeptPName}";
                    _tmpl += "      </div>";
                    return _tmpl;
                }
            },
            list: function () {
                var _multy = currentVariable.options.multy ? "1" : "0",
                    _type = currentVariable.options.type;
                var _tmpl = "<script id=\"tmpl\" type=\"text/x-jquery-tmpl\">";
                _tmpl += "{{each rows}}";
                _tmpl += "<li grand='${GrandNo}'>";
                _tmpl += ulitity.tmpl.right[_type](_multy);
                _tmpl += "  <div class=\"body-item-left\">";
                _tmpl += "{{if IsDept == '1'}}";
                _tmpl += "      <div class=\"body-item-icon org-icon\"></div>";
                _tmpl += "{{else}}";
                _tmpl += "  {{if SexName == '男'}}";
                _tmpl += "      <div class=\"body-item-icon complex-male\"></div>";
                _tmpl += "  {{else}}";
                _tmpl += "      <div class=\"body-item-icon complex-female\"></div>";
                _tmpl += "  {{/if}}";
                _tmpl += "{{/if}}";
                _tmpl += "  </div>";
                _tmpl += "  <div class=\"body-item-middle\" no='${No}'>";
                _tmpl += ulitity.tmpl.middle[_type]();
                _tmpl += "  </div>";
                _tmpl += "</li>";
                _tmpl += "{{/each}}";
                _tmpl += "<\/script>";
                return _tmpl;
            },
            selected: function () {
                var _tmpl = "<script id=\"tmpl\" type=\"text/x-jquery-tmpl\">";
                _tmpl += "{{each rows}}";
                _tmpl += "  <li id='s_${no}' name='${name}' no='${no}' type='${type}'>";
                _tmpl += "      <div class=\"complex-selected-item\">${name}</div>";
                _tmpl += "      <i class='selected-close'/>";
                _tmpl += "  </li>";
                _tmpl += "{{/each}}";
                _tmpl += "<\/script>";
                return _tmpl;
            }
        },
        scroll: {
            //list: function () {
            //    if (!scrollVariable["list"]) {
            //        scrollVariable["list"] = new JRoll("#complex-body-content");
            //    } else {
            //        scrollVariable["list"].scrollTo(0, 0, 0);
            //        scrollVariable["list"].refresh();
            //    }
            //},
            selected: function () {
                var scrollWidth = $("#complex-selected-body li").length * 60;
                $("#complex-selected-body ul").css("width", scrollWidth + "px");
                if (!scrollVariable["selected"]) {
                    scrollVariable["selected"] = new JRoll("#complex-selected-body", { scrollX: true, scrollY: false });
                } else {
                    scrollVariable["selected"].scrollTo(0, 0, 0);
                    scrollVariable["selected"].refresh();
                }
            }
        },
        init: {
            type: function (value) {
                var _no = "10001";
                if (value == "user") {
                    currentVariable.options.search_url = "/tappUser/SearchUser";
                    currentVariable.options.url = "/tappUser/SelectUser";
                    currentVariable.options.parameter = "";
                } else if (value == "dept") {
                    currentVariable.options.search_url = "/tappDept/SearchDept";
                    currentVariable.options.url = "/tappDept/SelectDept";
                    currentVariable.options.parameter = "";
                } else if (value == "custom") {
                    currentVariable.options.search_url = "/Role/SearchRole";
                    currentVariable.options.url = "/Role/SelectRole";
                    currentVariable.options.parameter = "";
                } else if (value == "common") {
                    currentVariable.options.search_url = "/wmp/api/searchcommon";
                    currentVariable.options.url = "/wmp/api/common/";
                    currentVariable.options.parameter = "";
                    _no = "0000";
                }
                return _no;
            },
            render: function (layer) {
                var _c = currentObject.parents("div[complex-key]");
                if (_c.length > 0) {
                    var _data = currentObject.parents("div[complex-key]").attr("value");
                    if (_data) {
                        _data = JSON.parse(_data);
                        $(_data).each(function () {
                            if (this.type == "ApprovalRole") {
                                this.no = this.no.replace('|', '-');
                            }
                            if (this.type == "ProductLine") {
                                this.no = "3001";
                            }
                        });
                        var _html = $(ulitity.tmpl.selected()).filter("#tmpl").tmpl({
                            rows: _data
                        });
                        $(layer).find(".complex-selected-body ul").append(_html);
                    }
                }
            },
            selected: function () {
                $("#complex-selected-body li").each(function () {
                    var _name = $(this).attr("name"),
                        _no = $(this).attr("no"),
                        _type = $(this).attr("type");

                    if (_type == "ProductLine") {
                        $("#component_3001").addClass("selected");
                    } else if (_type == "UnitRole") {
                        $("[c_name='n_" + _name + "']").addClass("selected");
                    } else {
                        $("#component_" + _no).addClass("selected");
                    }
                });
            }
        },
        close: function () {
            if ($(".complex-container .dropdown-menu").is(':visible')) {
                $(".complex-container .dropdown-menu").removeClass("show");
            }
        },
        compatible: function () {
            if (currentVariable) {
                var _c = currentObject.parent().parent().parent();
                if (_c.attr("complex-key")) {
                    if (_c.attr("complex-title")) {
                        currentVariable.options.title = _c.attr("complex-title");
                    }

                    if (_c.attr("complex-compose")) {
                        currentVariable.options.compose = _c.attr("complex-compose");
                    }

                    if (_c.attr("complex-multy")) {
                        currentVariable.options.multy = (_c.attr("complex-multy") == "true");
                    }

                    if (_c.attr("complex-confirm")) {
                        var _confirmFun;
                        try {
                            eval("_confirmFun=" + _c.attr("complex-confirm"));
                        } catch (ee) { }
                        if (_confirmFun && $.isFunction(_confirmFun)) {
                            currentVariable.on("confirm", function (data) {
                                _confirmFun(data);
                            });
                        }
                    }
                }
            }
        }
    };

    complex = function ($dom, options) { return this.init($dom, options); };
    complex.prototype = {
        init: function ($dom, options) {
            this["options"] = options,
                this["event-array"] = { confirm: null };
            $dom.each(function () {
                $(this).html(ulitity.render());
            });

            $dom.off("click", "button");
            $dom.on("click", "button", function (e) {
                if (!!$(this).attr("disabled")) { return; }
                currentObject = $(this),
                    scrollVariable = {},
                    currentVariable = Variable[options.key];
                ulitity.compatible();
                layer.open({
                    title: '<span class="layer_back"></span><span>' + currentVariable.options.title + '</span>',
                    content: ulitity.container(),
                    success: function ($layer, index) {
                        ulitity.event.fix($layer);
                        ulitity.init.render($layer);

                        var initNo = "10001";
                        if (currentVariable.options.compose) {
                            var cArray = currentVariable.options.compose.split(',');
                            if (cArray && cArray.length > 0) {
                                initNo = ulitity.init.type(cArray[0]);
                                currentVariable.options.type = cArray[0];
                            }
                        } else {
                            initNo = ulitity.init.type("user");
                        }
                        $($layer).find(".complex-type").html($($layer).find(".dropdown-menu li[value='" + currentVariable.options.type + "']").text());
                        setTimeout(function () {
                            ulitity.post($layer, initNo);
                        }, 500);
                    }
                });
            });

            if (document.removeEventListener) {
                document.removeEventListener("click", ulitity.close);
            } else if (document.detachEvent) { /*IE 8*/
                document.detachEvent("click", ulitity.close);
            }
            document.addEventListener("click", ulitity.close, false);

            return this;
        },
        on: function (event, callback) {
            this["event-array"][event] = callback;
            return this;
        },
        exec: function (event, $dom, data) {
            var _event = this["event-array"][event];
            if (_event) {
                _event.call(this, $dom, data);
            }
        }
    };
    var methods = {
        init: function (options) {
            var $this = $(this),
                setting = {
                    type: "user",
                    multy: false,
                    confirm: null,
                    title: "",
                    compose: ""
                },
                _key = "complext-" + new Date().getTime() + "-" + Math.random().toString(36).substr(2);
            setting = $.extend(setting, options);
            Variable[_key] = new complex($this, {
                key: _key,
                multy: setting.multy,
                type: setting.type,
                title: setting.title,
                compose: setting.compose
            });

            if ($.isFunction(setting.confirm)) {
                Variable[_key].on("confirm", function (data) {
                    setting.confirm(data);
                })
            }

            $this.attr("complex-key", _key);
            return $this;
        },
        key: function ($this) {
            return $this.attr("complex-key");
        },
        config: function () {
            return Variable[methods.key($(this))];
        },
        get: function () {
            var value = $(this).attr("value");
            return value ? JSON.parse(value) : [];
        },
        set: function (data) {
            if (!data || data.length == 0) { return; }
            $(this).attr("value", JSON.stringify(data));

            var _text = "";
            $(data).each(function () {
                _text += this.name + ",";
            });
            if (_text.length > 0) {
                _text = _text.substring(0, _text.length - 1);
            }
            $(this).find("input.form-control").val(_text);
        },
        empty: function () {
            $(this).attr("value", JSON.stringify([]));
            $(this).find("input.form-control").val("");
            return $(this);
        },
        enable: function () {
            $(this).removeClass("disabled");
            $(this).find("input,button").removeAttr("disabled");
            return $(this);
        },
        disabled: function () {
            $(this).addClass("disabled");
            $(this).find("input,button").attr("disabled", true);
            return $(this);
        },
        readonly: function () {
            $(this).WmpComplex("disabled");
            $(this).find("span").remove();
            $(this).find("div.input-group").css("width", "100%");
            return $(this);
        },
        multy: function (value) {
            Variable[methods.key($(this))].options.multy = value;
            return $(this);
        },
        title: function (value) {
            Variable[methods.key($(this))].options.title = value;
            return $(this);
        },
        compose: function (value) {
            Variable[methods.key($(this))].options.compose = value;
            return $(this);
        },
        confirm: function (fun) {
            if ($.isFunction(fun)) {
                Variable[methods.key($(this))].on("confirm", function (data) {
                    return fun(data);
                });
            }
        }
    };
    $.fn.WmpComplex = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method' + method + 'does not exist');
        }
    };
    window.WmpComplex = complex;
}($, window));